package com.cskaoyan.day24.tcp2;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Serve {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        Socket socket = serverSocket.accept();
        InputStream in = socket.getInputStream();

        DataInputStream dataInputStream = new DataInputStream(in);
        long strLen = dataInputStream.readLong();
        byte[] bytes = new byte[1024];
        int c = in.read(bytes);
        System.out.println(new String(bytes, 0, (int) (strLen)));
        System.out.println("输入字符串读取完成");

        long strFileLen = dataInputStream.readLong();
        long len = 0;
        int count;

        FileOutputStream out = new FileOutputStream("zserve/b.txt");
        char[] chars = new char[1024];
        System.out.println("开始接收文本文件并且输入到控制台：");
        while ((count = in.read(bytes)) != -1) {
            String str = new String(bytes, 0, count);
            System.out.println(new String(bytes, 0, count));
            if (str.endsWith("end")) {
                System.out.println(new String(bytes, 0, count - "end".length()));
            }

        }
        System.out.println("接收完成！");

        System.out.println("开始接收文本文件并且出到文件：");
        while ((count = in.read(bytes)) != -1) {
            String str = new String(bytes, 0, count);
            out.write(bytes, 0, count);
            if (str.endsWith("end")) {
                out.write(bytes, 0, count - "end".length());
            }

        }
        out.write(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).getBytes());
        System.out.println("接收完成！");


        out.close();
        socket.close();
        serverSocket.close();

    }
}
